#include "dialog.h"
#include "ui_dialog.h"
#include <QtCore/QCoreApplication>

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    listWidget = ui->listWidget;
    UdpSofd=new QUdpSocket(this);
    TcpSofd=new QTcpSocket(this);
    filesocket=new QTcpSocket(this);
    listWidget = ui->listWidget;
    //绑定套接字
    if(!UdpSofd->bind(QHostAddress::Any,8000))
    {
       qWarning()<< "Failed to bind UDP socket:" << UdpSofd->errorString();
    }
    else
    {
       qDebug()<< "UDP sockrt successfully bound to port 8000";
    }
    //点击发送广播搜索设备
    connect(ui->pushButton_search,&QPushButton::clicked,this,&Dialog::SofdSend);
    //连接接收数据的信号槽
    connect(UdpSofd,&QUdpSocket::readyRead,this,&Dialog::GetFirstText);
    //连接TCP信号槽
    connect(ui->pushButton_connect, &QPushButton::clicked, this, &Dialog::ConnectToServer);
    //接收服务器消息
    connect(TcpSofd, &QTcpSocket::readyRead, this, &Dialog::ReadServerResponse);
    //心跳包连接
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this,SLOT(heartTimer()));
    //连接断开连接信号槽
    connect(ui->pushButton_disconnect, &QPushButton::clicked, this, &Dialog::DisconnectFromServer);
}
    Dialog::~Dialog()
    {
        delete ui;
        delete UdpSofd;// 关闭UDP的套接字
        delete TcpSofd;//关闭TCP的套接字
        delete filesocket;//关闭TCP的点表
    }

//发送广播搜索设备
void Dialog::SofdSend()
{
    //设置广播IP地址
    QHostAddress BroadcastAddress("192.168.42.255");
    //设置广播内容
    QString message("tianwanggaidihu");
    QByteArray BroadcastMessage=message.toUtf8();
    //设置端口号
    qint16 BroadcastPort=8000;
    //发送广播
    UdpSofd->writeDatagram(BroadcastMessage, BroadcastAddress, BroadcastPort);
    qDebug() << "Broadcast message sent!";
}
//接收处理消息
void Dialog::GetFirstText()
{
    //检查是否有数据待处理
    while(UdpSofd->hasPendingDatagrams())
    {
        QByteArray buffer;
        buffer.resize(UdpSofd->pendingDatagramSize());
        //获取服务器IP和端口号
        QHostAddress sender;
        quint16 senderPort;
        //读取数据
        int bytesRead=UdpSofd->readDatagram(buffer.data(),buffer.size(),&sender,&senderPort);
        if(bytesRead>0)
        {
           IP=sender;
           Port=senderPort;
           //输出到ui界面
           QString ShowIP = sender.toString();
           ui->textBrowser->append(ShowIP);
           QString text(buffer);
           qDebug() << "Received message: "<<text;
           //判断是不是我的设备
           if(text=="baotazhenheyao")
           {
              qDebug()<<"This is my device"<< sender << senderPort ;
              QListWidgetItem *item = new QListWidgetItem(QString("%1:%2").arg(sender.toString()).arg(senderPort));
              listWidget->addItem(item);
           }
           else
           {
              qDebug()<<"This is not my device";
              //QListWidgetItem *item = new QListWidgetItem(QString("%1:%2").arg(sender.toString()).arg(senderPort));
              //listWidget->addItem(item);
           }

        }
    }
}
//TCP连接
void Dialog::ConnectToServer()
{
    //获取列表中选中的项
    QListWidgetItem *selectedItem = listWidget->currentItem();
    if (!selectedItem)
    {
        qDebug() << "No device selected.";
        return;
    }
    //解析IP和端口
    QStringList ipPort = selectedItem->text().split(':');
    QHostAddress selectedIP(ipPort[0]);
    quint16 selectedPort = ipPort[1].toUShort();
    //连接服务器
    TcpSofd->connectToHost(selectedIP, selectedPort);
    //连接成功检测
    if(TcpSofd->waitForConnected(3000))
    {
        qDebug()<<"Successful connect to server";
        ui->textBrowser->append("Successful connect to server");
        //给服务器发送点表
        json["type"] = 1;//将json格式 "type" 字段的值设置为 1。
        // 创建JSON文档
        QJsonDocument jsonDoc(json);
        // 将JSON文档转换为字节数组
        QByteArray jsonData = jsonDoc.toJson();
        // 发送JSON数据
        TcpSofd->write(jsonData);
        SendFile();
    }
    else
    {
        qDebug()<<"connect failure";
        ui->textBrowser->append("connect failure");
    }
    //下发心跳包
    timer->start(2000); // 间隔2秒发一次
}
// 断开连接槽函数
void Dialog::DisconnectFromServer()
{
    // 如果TCP套接字已连接，则关闭连接
    if (TcpSofd->state() == QAbstractSocket::ConnectedState)
    {
        TcpSofd->close(); // 直接关闭套接字
        qDebug() << "TCP socket successfully closed";
        ui->textBrowser->append("TCP socket successfully closed");
        // 停止心跳包计时器
        timer->stop();
    }
    else
    {
        qDebug() << "Not connected to any server";
        ui->textBrowser->append("Not connected to any server");
    }
}
// 读取服务器内容
void Dialog::ReadServerResponse()
{
    while (TcpSofd->bytesAvailable() > 0) {
        QByteArray response = TcpSofd->readAll();
        QString text = QString::fromUtf8(response);
        // 检查是否为心跳包
        if (text == "heartbeat")
        {
            qDebug() << "Process living";
        } else {
            // 解析JSON数据
            QJsonDocument jsonDoc = QJsonDocument::fromJson(response);
            if (!jsonDoc.isNull()) {
                // 检查JSON文档是否为对象
                if (jsonDoc.isObject()) {
                    QJsonObject jsonObj = jsonDoc.object();
                    qDebug() << "Received JSON data:" << jsonObj;
                    // 将JSON对象写入文件
                    QFile writeFile("/res.qrc/json/node.json");
                    if (writeFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
                        writeFile.write(jsonDoc.toJson());
                        writeFile.close();
                        qDebug() << "JSON data written to node.json";
                    } else {
                        qDebug() << "Failed to open node.json";
                    }
                } else {
                    qDebug() << "Received JSON data is not an object";
                }
            } else {
                qDebug() << "Failed to parse JSON data";
            }
        }
    }
}
//发送点表
void Dialog::SendFile()
{
    // 确保套接字未连接
    if (filesocket->state() != QAbstractSocket::UnconnectedState)
    {
        filesocket->disconnectFromHost();
    }
    // 连接到主机
    filesocket->connectToHost(IP, 8001);
    if (!filesocket->waitForConnected(3000))
    {
        qDebug() << "Failed to connect to host for sending file";
        return;
    }
    QFile readFile(":/json/node.json");
    if (!readFile.open(QIODevice::ReadOnly))
    {
        qDebug() << "Failed to open file for reading";
        return;
    }
    QByteArray file = readFile.readAll();
    qint64 bytesWritten = filesocket->write(file);
    if (bytesWritten == -1)
    {
        qDebug() << "Failed to write file to socket";
    }
    else
    {
        qDebug() << "Successfully sent file, bytes written:" << bytesWritten;
    }
    readFile.close();
    filesocket->waitForBytesWritten();
    filesocket->close();
}
//发送心跳包
void Dialog::heartTimer()
{
    // 添加其他键值对
    json["type"] = 3;
    // 创建JSON文档
    QJsonDocument jsonDoc(json);
    // 将JSON文档转换为字节数组
    QByteArray jsonData = jsonDoc.toJson();
    // 发送JSON数据
    TcpSofd->write(jsonData);
}
